import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user' // 接口
import {
  type loginFormData,
  type loginReponseData,
  type userInfoResponseData,
} from '@/api/user/type'
import { type UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import default_avatar from '@/assets/images/default_avatar.png'
import { ref } from 'vue'
export const useUserStore = defineStore('User', () => {
  // 数据
  const token = ref('')
  token.value = GET_TOKEN()
  // 方法
  async function userLogin(params: loginFormData) {
    try {
      const result: loginReponseData = await reqLogin(params)
      if (result.code === 200) {
        token.value = result.data
        SET_TOKEN(result.data) // 断言
        return '登录成功'
      } else {
        return Promise.reject(new Error(result.message))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

  //获取用户信息方法
  const userName = ref('')
  const avatarImg = ref(default_avatar)
  async function userInfo() {
    const result: userInfoResponseData = await reqUserInfo()
    if (result.code == 200) {
      const { name, avatar, buttons } = result.data
      userName.value = name
      avatarImg.value = avatar
      return '获取用户信息成功'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }

  // 退出登录
  async function userLogout() {
    const result: any = await reqLogout()
    if (result.code === 200) {
      token.value = ''
      userName.value = ''
      avatarImg.value = default_avatar
      REMOVE_TOKEN()
      return '退出登录成功'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }
  return { userLogin, userInfo, userLogout, token, userName, avatarImg }
})
